﻿using Minio;
using Minio.ApiEndpoints;
using Minio.DataModel;
using Minio.DataModel.Args;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using NPOI.SS.Formula.Functions;

namespace DeHeng_Mes.Utils
{
    public class MinioHelper
    {
        private readonly IMinioClient _minioClient;


        public MinioHelper(string endpoint, string accessKey, string secretKey, bool useSSL = false)
        {
            try
            {
                _minioClient = new MinioClient()
                    .WithEndpoint(endpoint)
                    .WithCredentials(accessKey, secretKey)
                    .WithSSL(useSSL)
                    .Build();
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"初始化 Minio 客户端失败: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 检查桶是否存在
        /// </summary>
        public async Task<bool> BucketExistsAsync(string bucketName)
        {
            try
            {
                var args = new BucketExistsArgs().WithBucket(bucketName);
                return await _minioClient.BucketExistsAsync(args);
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"检查桶 '{bucketName}' 是否存在时出错: {ex.Message}");
                return false; // 根据需要返回默认值
            }
        }

        /// <summary>
        /// 创建桶
        /// </summary>
        public async Task<bool> CreateBucketAsync(string bucketName)
        {
            if (string.IsNullOrEmpty(bucketName))
            {
                throw new ArgumentException("Bucket name cannot be null or empty.", nameof(bucketName));
            }

            var args = new BucketExistsArgs().WithBucket(bucketName);
            bool exists = await _minioClient.BucketExistsAsync(args);
            if (!exists)
            {
                await _minioClient.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucketName));
                Tools.ProduceLogTextError($"Bucket '{bucketName}' created successfully.");
                return true; // 表示成功创建存储桶
            }
            else
            {
                Tools.ProduceLogTextError($"Bucket '{bucketName}' already exists.");
                return false; // 表示存储桶已经存在
            }
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        public async Task UploadFileAsync(string bucketName, string objectName, string filePath)
        {
            try
            {
                var args = new PutObjectArgs()
                    .WithBucket(bucketName)
                    .WithObject(objectName)
                    .WithFileName(filePath)
                    .WithContentType("application/octet-stream");

                await _minioClient.PutObjectAsync(args);
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"上传文件 '{filePath}' 到桶 '{bucketName}' 时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        public async Task DownloadFileAsync(string bucketName, string objectName, string filePath)
        {
            try
            {
                var args = new GetObjectArgs()
                    .WithBucket(bucketName)
                    .WithObject(objectName)
                    .WithFile(filePath);

                await _minioClient.GetObjectAsync(args);
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"从桶 '{bucketName}' 下载对象 '{objectName}' 时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        public async Task DeleteFileAsync(string bucketName, string objectName)
        {
            try
            {
                var args = new RemoveObjectArgs()
                    .WithBucket(bucketName)
                    .WithObject(objectName);

                await _minioClient.RemoveObjectAsync(args);
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"删除桶 '{bucketName}' 中的对象 '{objectName}' 时出错: {ex.Message}");
            }
        }


        /// <summary>
        /// 列出桶中的文件
        /// </summary>
        public async Task ListFilesAsync(string bucketName)
        {
            var args = new ListObjectsArgs()
                .WithBucket(bucketName)
                .WithRecursive(true);

            var objects = _minioClient.ListObjectsEnumAsync(args);

            try
            {
                var enumerator = objects.GetAsyncEnumerator();
                try
                {
                    while (await enumerator.MoveNextAsync())
                    {
                        var item = enumerator.Current;
                        Tools.ProduceLogTextError($"对象: {item.Key}, 大小: {item.Size}, 更新时间: {item.LastModified}");
                    }
                }
                finally
                {
                    await enumerator.DisposeAsync();
                }
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"遍历文件错误：{ex.Message}");
            }
        }
    }

}